package com.awspaass.user.apps.restaurant;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.actionsoft.bpms.commons.database.ColumnMapRowMapper;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.bind.annotation.Controller;
import com.actionsoft.bpms.server.bind.annotation.Mapping;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.awspaas.user.apps.shhtaerospaceindustrial.sms.SmsUtil;
import com.awspaas.user.apps.shhtaerospaceindustrial.util.CoreUtil;

@Controller
public class AppCmdProductReservationCancel {

	/*
	 * 食堂调度取消已接单产品订单
	 */
	@Mapping("com.awspaass.user.apps.ProductReservation_dispatchCancelAssign")
	public String dispatchCancelAssign(String bindid , UserContext uc) {
		JSONObject returnData = new JSONObject();
		String guanliyuan =uc.getUserModel().getUserName();//办理人名称
		String telephone =uc.getUserModel().getMobile();//节点办理人电话
		if(null == bindid || "".equals(bindid)  ) {
			returnData.put("status", "0");
			returnData.put("message", "请检查参数!");
			return returnData.toString();
		}
		try {
			String orderSql = "select ID,APPLYNAME,CONTACTPHONE,ORDERDATE,AREA,GETFOODTIME,PERIOD from BO_EU_SHSYST_FOODORDER_HEAD where bindid='"+bindid+"' ";
			
			String getfoodtime = CoreUtil.objToStr(DBSql.getString(orderSql, "GETFOODTIME"));// 取货时间
			String applyname = CoreUtil.objToStr(DBSql.getString(orderSql, "APPLYNAME"));// 联系人
			String contactphone = CoreUtil.objToStr(DBSql.getString(orderSql, "CONTACTPHONE"));// 联系电话
			String AREA = CoreUtil.objToStr(DBSql.getString(orderSql, "AREA"));// 预定食堂
			String stquerySql="select item.cnname areaname,item.exttext2 from Bo_Act_Dict_Kv_Item item "
					+ "left join BO_ACT_DICT_KV_MAIN main on item.bindid = main.bindid " + "where substr('"
					+ AREA + "',0,2)=item.itemno and main.dictkey = 'shdininghallarea'";
			String areaName = CoreUtil.objToStr(DBSql.getString(stquerySql, "areaname"));
			String exttext2 = CoreUtil.objToStr(DBSql.getString(stquerySql, "exttext2"));//食堂调度电话号
			String[] telephonenum =exttext2.split("、");
			String param = "{'CONTACTPERSON':'"+applyname+"','YCDATEAREA':'"+getfoodtime+areaName+
					"','GUANLIYUAN':'"+guanliyuan+"','TELEPHONE':'"+telephone+"'}";
			String messageguanliyuan = "{'CONTACTPERSON':'"+applyname+"','YCDATEAREA':'"+getfoodtime+areaName+
					"','TELEPHONE':'"+contactphone+"'}";
			String updateAssignSql = "update BO_EU_SHSYST_FOODORDER_HEAD set ORDERSTATUS='6' where BINDID ='" + bindid + "'";
			DBSql.update(updateAssignSql);
			SmsUtil.sendSms(contactphone, "SMS_256000119", param);//取消成功给用户发短信提醒
			if(telephonenum.length > 0) {
				for (int i = 0; i < telephonenum.length; i++) {
					SmsUtil.sendSms(telephonenum[i], "SMS_256115274", messageguanliyuan);//取消成功给调度发消息
				}
			}
			returnData.put("status", "0");
			returnData.put("message", "取消成功！");
		} catch (Exception e) {
			returnData.put("status", "1");
			returnData.put("message", e.getMessage());
			e.printStackTrace();

		}
		return returnData.toString();

	}
	/*
	 * 加载食堂调度已接产品订单的可取消的所有订单
	 */
	@Mapping("com.awspaass.user.apps.ProductReservation_dispatchDetails")
	public static String getProductReservation_dispatchDetails(UserContext uc,String ycbegin,String ycend,String ycperson) {
		String userId = uc.getUID();
		String areaid = "";
		String 	areaidsql="select t.itemno areaid from Bo_Act_Dict_Kv_Item t left join  BO_ACT_DICT_KV_MAIN a on t.bindid=a.bindid  "
						+ "where t.dictkey='shdininghallarea' and t.enname like '%"+userId+"%'";
		List<Map<String, Object>> areaidList = DBSql.query(areaidsql, new ColumnMapRowMapper(), new Object[] {});
		 StringBuffer pk_xmplanpks = new StringBuffer("('");
		if(areaidList.size() >0) {
			for (int j = 0; j < areaidList.size(); j++) {
				Map<String, Object> urlMap = areaidList.get(j);
				String stid = CoreUtil.objToStr(urlMap.get("AREAID"));
				if (j < areaidList.size() - 1) {
					pk_xmplanpks.append(stid);
					pk_xmplanpks.append("','");
				} else {
					pk_xmplanpks.append(stid);
					pk_xmplanpks.append("')");
				}
			}
		}
		if(pk_xmplanpks.length() >2) {
			areaid=pk_xmplanpks.toString();
		}
		JSONObject result = new JSONObject();
		String checksql="";
		String sql="";
		if(!"".equals(ycbegin)) {//取货时间大于等于
			sql = " and t.GETFOODTIME >='" + ycbegin + "' ";
			checksql +=sql;
		}
		if(!"".equals(ycend)) { //取货时间小于等于
			sql =" and t.GETFOODTIME <='" + ycend + "' ";
			checksql +=sql;
		}
		if(!"".equals(ycperson)) { //预订人
			sql =" and t.APPLYNAME like '%" + ycperson + "%' ";
			checksql +=sql;
		}
		try {
			if(!"".equals(checksql)) {
				 String querySql ="";
				    if(!"".equals(areaid)) {
				    	querySql = "select t.APPLYUID,t.ORDERSTATUS,t.APPLYNAME,t.GETFOODTIME,t.AREA,t.PERIOD ,t.BINDID from  BO_EU_SHSYST_FOODORDER_HEAD  t  where "
								+ "t.ORDERSTATUS in('2') " + checksql +  " and t.AREA  in " + areaid + " order by  t.GETFOODTIME  asc ";
				    }else{
				    	querySql = "select t.APPLYUID,t.ORDERSTATUS,t.APPLYNAME,t.GETFOODTIME,t.AREA,t.PERIOD ,t.BINDID from  BO_EU_SHSYST_FOODORDER_HEAD  t  where "
				    			+ "t.ORDERSTATUS in('2')  " + checksql + "  order by  t.GETFOODTIME  asc ";
				    }
					List<Map<String, Object>> urlList = DBSql.query(querySql, new ColumnMapRowMapper(), new Object[] {});
					if (urlList == null || urlList.isEmpty()) {
						JSONArray itemArray = new JSONArray();
						result.put("status", "0");
						result.put("item", itemArray);
					}
		
					JSONArray itemArray = new JSONArray();
					for (int i = 0; i < urlList.size(); i++) {
						Map<String, Object> urlMap = urlList.get(i);
						JSONObject item = new JSONObject();
						String APPLYNAME = CoreUtil.objToStr(urlMap.get("APPLYNAME"));// 预定人
						String GETFOODTIME = CoreUtil.objToStr(urlMap.get("GETFOODTIME"));// 取货时间
						String PERIOD = CoreUtil.objToStr(urlMap.get("PERIOD"));// 取菜时间段 0:午餐时段|1:晚餐时段
						String AREA = CoreUtil.objToStr(urlMap.get("AREA"));// 食堂区域
						String ORDERSTATUS = CoreUtil.objToStr(urlMap.get("ORDERSTATUS"));// 订单状态
						String areaName = CoreUtil
								.objToStr(DBSql.getString("select item.cnname areaname from Bo_Act_Dict_Kv_Item item "
										+ "left join BO_ACT_DICT_KV_MAIN main on item.bindid = main.bindid " + "where substr('"
										+ AREA + "',0,2)=item.itemno and main.dictkey = 'shdininghallarea'", "areaname"));
						String BINDID = CoreUtil.objToStr(urlMap.get("BINDID"));// 流程实例id	
						item.put("applyname", APPLYNAME);	// 预定人
						item.put("getfoodtime", GETFOODTIME);// 取货时间
						item.put("period", PERIOD);// 取菜时间段0:午餐时段|1:晚餐时段
						item.put("area", areaName);// 食堂区域
						item.put("bindid", BINDID);
						item.put("orderstatus", ORDERSTATUS);// 订单状态
						itemArray.add(item);
					}
					result.put("status", "0");
					result.put("item", itemArray);
			}else {
				Date now = new Date();// 系统日期
				SimpleDateFormat DateFormat = new SimpleDateFormat("yyyy-MM-dd");
				String today = DateFormat.format(now);// 日期
				Calendar calendar = Calendar.getInstance();  
			    calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + 6);  
			    Date endtoday = calendar.getTime();  
			    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
			    String enddate = format.format(endtoday);  
			    String querySql ="";
			    if(!"".equals(areaid)) {
			    	querySql = "select t.APPLYUID,t.ORDERSTATUS,t.APPLYNAME,t.GETFOODTIME,t.AREA,t.PERIOD ,t.BINDID from  BO_EU_SHSYST_FOODORDER_HEAD  t  where "
							+ "t.ORDERSTATUS in('2') and t.GETFOODTIME >='" + today + "' and t.GETFOODTIME  <='" + enddate + "' and t.AREA  in " + areaid + "  order by  t.GETFOODTIME  asc ";
			    }else{
			    	querySql = "select t.APPLYUID,t.ORDERSTATUS,t.APPLYNAME,t.GETFOODTIME,t.AREA,t.PERIOD ,t.BINDID from  BO_EU_SHSYST_FOODORDER_HEAD  t where "
			    			+ "t.ORDERSTATUS in('2') and t.GETFOODTIME >='" + today + "' and t.GETFOODTIME  <='" + enddate + "' order by  t.GETFOODTIME  asc ";
			    }
				List<Map<String, Object>> urlList = DBSql.query(querySql, new ColumnMapRowMapper(), new Object[] {});
				if (urlList == null || urlList.isEmpty()) {
					JSONArray itemArray = new JSONArray();
					result.put("status", "0");
					result.put("item", itemArray);
				}
	
				JSONArray itemArray = new JSONArray();
				for (int i = 0; i < urlList.size(); i++) {
					Map<String, Object> urlMap = urlList.get(i);
					JSONObject item = new JSONObject();
					String APPLYNAME = CoreUtil.objToStr(urlMap.get("APPLYNAME"));// 预定人
					String GETFOODTIME = CoreUtil.objToStr(urlMap.get("GETFOODTIME"));// 取货时间
					String PERIOD = CoreUtil.objToStr(urlMap.get("PERIOD"));// 取菜时间段 0:午餐时段|1:晚餐时段
					String AREA = CoreUtil.objToStr(urlMap.get("AREA"));// 食堂区域
					String ORDERSTATUS = CoreUtil.objToStr(urlMap.get("ORDERSTATUS"));// 订单状态
					String areaName = CoreUtil
							.objToStr(DBSql.getString("select item.cnname areaname from Bo_Act_Dict_Kv_Item item "
									+ "left join BO_ACT_DICT_KV_MAIN main on item.bindid = main.bindid " + "where substr('"
									+ AREA + "',0,2)=item.itemno and main.dictkey = 'shdininghallarea'", "areaname"));
					String BINDID = CoreUtil.objToStr(urlMap.get("BINDID"));// 流程实例id	
					item.put("applyname", APPLYNAME);	// 预定人
					item.put("getfoodtime", GETFOODTIME);// 取货时间
					item.put("period", PERIOD);// 取菜时间段0:午餐时段|1:晚餐时段
					item.put("area", areaName);// 食堂区域
					item.put("bindid", BINDID);
					item.put("orderstatus", ORDERSTATUS);// 订单状态
					itemArray.add(item);
				}
				result.put("status", "0");
				result.put("item", itemArray);
			}
		} catch (Exception e) {

			result.put("status", "1");
			result.put("message", e.getMessage());
			e.printStackTrace();
		}

		return result.toString();
	}

	/*
	 * 用户取消已接单订单  ORDERSTATUS
	 */
	@Mapping("com.awspaass.user.apps.ProductReservation_userCancelAssign")
	public String userCancelAssign(String bindid, UserContext uc) {
		JSONObject returnData = new JSONObject();
		
		if(null == bindid || "".equals(bindid)  ) {
			returnData.put("status", "0");
			returnData.put("message", "请检查参数!");
			return returnData.toString();
		}
		
		try {
			String querySql = "select t.APPLYUID,t.ORDERSTATUS,t.APPLYNAME,t.GETFOODTIME,t.AREA,t.CONTACTPHONE ,t.BINDID from  BO_EU_SHSYST_FOODORDER_HEAD  t  WHERE t.BINDID = "
					+ "'" + bindid + "'";
			String AREA = CoreUtil.objToStr(DBSql.getString(querySql, "AREA"));// 取货食堂
			String GETFOODTIME = CoreUtil.objToStr(DBSql.getString(querySql, "GETFOODTIME"));// 取货日期
			String APPLYUID = CoreUtil.objToStr(DBSql.getString(querySql, "APPLYUID"));// 预定人id
			String APPLYNAME = CoreUtil.objToStr(DBSql.getString(querySql, "APPLYNAME"));// 预定人
			String CONTACTPHONE = CoreUtil.objToStr(DBSql.getString(querySql, "CONTACTPHONE"));// 预订人电话
			String ORDERSTATUS = CoreUtil.objToStr(DBSql.getString(querySql, "ORDERSTATUS"));// 订单状态
			String stquerySql="select item.cnname areaname,item.exttext2 from Bo_Act_Dict_Kv_Item item "
					+ "left join BO_ACT_DICT_KV_MAIN main on item.bindid = main.bindid " + "where substr('"
					+ AREA + "',0,2)=item.itemno and main.dictkey = 'shdininghallarea'";
			String areaName = CoreUtil.objToStr(DBSql.getString(stquerySql, "areaname"));//食堂名称
			String exttext2 = CoreUtil.objToStr(DBSql.getString(stquerySql, "exttext2"));//食堂调度电话号
			String[] telephonenum =exttext2.split("、");
			String message ="{'CONTACTPERSON':'" + APPLYNAME + "','YCDATEAREA':'" + GETFOODTIME+areaName+ "'}";
			String messageguanliyuan = "{'CONTACTPERSON':'"+APPLYNAME+"','YCDATEAREA':'"+GETFOODTIME+areaName+
					"','TELEPHONE':'"+CONTACTPHONE+"'}";
			String updateAssignSql = "update BO_EU_SHSYST_FOODORDER_HEAD set ORDERSTATUS='6' where BINDID ='" + bindid + "'";
			DBSql.update(updateAssignSql);
			if("1".equals(ORDERSTATUS)) {
				try {
					System.out.println("准备终止流程！流程号:" + bindid + "用户ID:" + APPLYUID);
					SDK.getProcessAPI().terminateById(bindid, APPLYUID);
				} catch (Exception e) {
					e.printStackTrace();
				}
				SmsUtil.sendSms(CONTACTPHONE, "SMS_255940124", message);//取消成功给用户发消息
				
			}else {
				SmsUtil.sendSms(CONTACTPHONE, "SMS_255940124", message);//取消成功给用户发消息
				if(telephonenum.length > 0) {
					for (int i = 0; i < telephonenum.length; i++) {
						SmsUtil.sendSms(telephonenum[i], "SMS_256115274", messageguanliyuan);//取消成功给调度发消息
					}
				}
				
			}
			
			returnData.put("status", "0");
			returnData.put("message", "取消成功！");
		} catch (Exception e) {
			returnData.put("status", "1");
			returnData.put("message", e.getMessage());
			e.printStackTrace();
		}

		return returnData.toString();

	}

	/*
	 * 加载用户预订完成的可取消的所有订单
	 * 此接口未用
	 */
	@Mapping("com.awspaass.user.apps.ProductReservation_userDetails")
	public static String getProductReservation_userDetails(UserContext uc) {
		String userId = uc.getUID();
		JSONObject result = new JSONObject();
		try {
			Date now = new Date();// 系统日期
//			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SimpleDateFormat DateFormat = new SimpleDateFormat("yyyy-MM-dd");
			//String detaildate = simpleDateFormat.format(now);// 时间时分秒
			String today = DateFormat.format(now);// 日期
			String querySql = "select t.ORDERSTATUS,t.YCDATE,t.ORDERSEL,t.AREA,t.ROOMNUM ,t.BINDID from  BO_EU_SH_FOODORDER  t  where "
					+ "t.ORDERSTATUS in('1','2') and t.YCDATE >='" + today + "' and t.APPLYID ='" + userId + "' order by  t.YCDATE  asc";
			List<Map<String, Object>> urlList = DBSql.query(querySql, new ColumnMapRowMapper(), new Object[] {});
			if (urlList == null || urlList.isEmpty()) {
				JSONArray itemArray = new JSONArray();
				result.put("status", "0");
				result.put("item", itemArray);
			}

			JSONArray itemArray = new JSONArray();
			for (int i = 0; i < urlList.size(); i++) {
				Map<String, Object> urlMap = urlList.get(i);
				JSONObject item = new JSONObject();
				String YCDATE = CoreUtil.objToStr(urlMap.get("YCDATE"));// 用餐时间
				System.out.println(YCDATE);
				String ORDERSEL = CoreUtil.objToStr(urlMap.get("ORDERSEL"));// 用餐时段 0:午餐|1:晚餐|2:早餐|3:夜宵
				String AREA = CoreUtil.objToStr(urlMap.get("AREA"));// 食堂区域
				String ORDERSTATUS = CoreUtil.objToStr(urlMap.get("ORDERSTATUS"));// 订单状态
				String areaName = CoreUtil
						.objToStr(DBSql.getString("select item.cnname areaname from Bo_Act_Dict_Kv_Item item "
								+ "left join BO_ACT_DICT_KV_MAIN main on item.bindid = main.bindid " + "where substr('"
								+ AREA + "',0,2)=item.itemno and main.dictkey = 'shdininghallarea'", "areaname"));
				String ROOMNUM = CoreUtil.objToStr(urlMap.get("ROOMNUM"));// 房间号
				String BINDID = CoreUtil.objToStr(urlMap.get("BINDID"));// 流程实例id
				
				Date timeLine = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(YCDATE + " 12:00:00");
				//System.out.println(timeLine);
				Date timeLine1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(YCDATE + " 17:00:00");
				Date timeLine2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(YCDATE + " 07:00:00");
				Date timeLine3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(YCDATE + " 21:00:00");
				//System.out.println(timeLine1);
				//System.out.println(now);
				//System.out.println(new Date(detaildate).getTime());
				if ("0".equals(ORDERSEL) && timeLine.getTime()
						- now.getTime() >= 4 * 60 * 60 * 1000) {// 0:午餐
					item.put("ycdate", YCDATE);
					item.put("ordersel", ORDERSEL);
					item.put("area", areaName);
					item.put("roomnum", ROOMNUM);
					item.put("bindid", BINDID);
					item.put("orderstatus", ORDERSTATUS);
					itemArray.add(item);
				} else if ("1".equals(ORDERSEL) && timeLine1.getTime()
						- now.getTime() >= 4 * 60 * 60 * 1000) {// 1:晚餐
					item.put("ycdate", YCDATE);
					item.put("ordersel", ORDERSEL);
					item.put("area", areaName);
					item.put("roomnum", ROOMNUM);
					item.put("bindid", BINDID);
					item.put("orderstatus", ORDERSTATUS);
					itemArray.add(item);
				}else if ("2".equals(ORDERSEL) && timeLine2.getTime()
						- now.getTime() >= 4 * 60 * 60 * 1000) {// 2:早餐
					item.put("ycdate", YCDATE);
					item.put("ordersel", ORDERSEL);
					item.put("area", areaName);
					item.put("roomnum", ROOMNUM);
					item.put("bindid", BINDID);
					item.put("orderstatus", ORDERSTATUS);
					itemArray.add(item);
				}else if ("3".equals(ORDERSEL) && timeLine3.getTime()
						- now.getTime() >= 4 * 60 * 60 * 1000) {// 3:夜宵
					item.put("ycdate", YCDATE);
					item.put("ordersel", ORDERSEL);
					item.put("area", areaName);
					item.put("roomnum", ROOMNUM);
					item.put("bindid", BINDID);
					item.put("orderstatus", ORDERSTATUS);
					itemArray.add(item);
				}

			}
			result.put("status", "0");
			result.put("item", itemArray);
		} catch (Exception e) {

			result.put("status", "1");
			result.put("message", e.getMessage());
			e.printStackTrace();
		}

		return result.toString();
	}

}
